﻿using System;
using System.Collections.Generic;
using HtmlAgilityPack;

namespace JoelAbrahamsson.Web.Common.HtmlFiltering
{
    public class NewLineToBreakTagFilter : ITextNodeFilter
    {
        public List<string> ExcludeDescendantsOfTags { get; set; }

        public NewLineToBreakTagFilter()
        {
            ExcludeDescendantsOfTags = new List<string>();
        }

        public string Filter(string text, HtmlNode originalNode)
        {
            foreach (string excludeDescendantsOfTag in ExcludeDescendantsOfTags)
            {
                if (IsDescendantOf(originalNode, excludeDescendantsOfTag))
                    return text;
            }

            return text.Replace(Environment.NewLine, "<br />");
        }

        private bool IsDescendantOf(HtmlNode node, string anscestorNodeName)
        {
            if (node.ParentNode == null)
                return false;

            if (node.ParentNode.Name.ToLower() == anscestorNodeName)
                return true;

            return IsDescendantOf(node.ParentNode, anscestorNodeName);
        }
    }
}
